﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.SqlClient;
using IronOne.SalesOne.BusinessObjects;
using System.Configuration;
using System.Web.Security;
using System.Security.Cryptography;
using System.IO;


namespace IronOne.SalesOne.DataObjects
{
    public class LinqUser
    {
        public int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["GridCount"]);

        public bool? UpdateIntranetUsername(string uname, string intraUName)
        {
            try
            {
                using (SODataDataContext db = DataContextFactory.CreateContext())
                {
                    aspnet_User us =
                        db.aspnet_Users.FirstOrDefault(p => p.IntranetUN.ToLower().Trim().Equals(intraUName.ToLower().Trim()));

                    if (us == null)
                    {
                        aspnet_User au = db.aspnet_Users.SingleOrDefault(p => p.UserName.Equals(uname));
                        au.IntranetUN = intraUName.ToLower().Trim();
                        db.SubmitChanges();
                        return true;
                    }
                }
                return false;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Return the intranet username, when given the username
        /// </summary>
        /// <returns>NULL - If user not linked</returns>
        public string IsLinkedUserCheck(string userName)
        {
            try
            {
                using (SODataDataContext db = DataContextFactory.CreateContext())
                {
                    string linkedUsername = db.aspnet_Users.SingleOrDefault(p => p.UserName.Equals(userName)).IntranetUN;
                    if (linkedUsername != null)
                    {
                        return linkedUsername;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Suren Manawatta
        /// 2012-10-31
        /// Send the username and password to Ceylinco db for authentication
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>True - Success Login</returns>
        public bool GetAuthUserOverCeylincoDb(string username, string password)
        {
            try
            {
                string connString = ConfigurationManager.ConnectionStrings["System.Data.SqlClient"].ConnectionString;
                string encryptedPassword = "";
                using (SqlConnection conn = new SqlConnection(connString))
                {
                    conn.Open();
                    SqlParameter myParam = new SqlParameter("@UsernameParam", SqlDbType.VarChar, 50);
                    myParam.Value = username;
                                     
                    string connIP = ConfigurationManager.AppSettings["CeylincoDBIP"];

                    SqlCommand myCommand = new SqlCommand("select PasswordED from [" + connIP + "].dwh.dbo.PASSWORD_NEW_SYSTEM " +
                                                          "where EMPID = @UsernameParam", conn);
                    
                    //SqlCommand myCommand = new SqlCommand("select PasswordED from password " +
                    //                                      "where EMPID = @UsernameParam", conn);
                    myCommand.Parameters.Add(myParam);
                    SqlDataReader myReader = myCommand.ExecuteReader();
                    while(myReader.Read())
                    {
                        encryptedPassword = myReader["PasswordED"].ToString();
                    }
                }
                PasswordED decdll = new PasswordED();
                string encryptedOrgPassword = decdll.encryptPassword(password);

                if (encryptedOrgPassword.Equals(encryptedPassword))
                {
                    return true;
                }
                return false;
            }
            catch (Exception e)
            {
                StreamWriter file = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\ZLog.txt", true);
                file.WriteLine(e.Message);
                file.WriteLine(e.InnerException);
                file.Close();

                return false;
            }
        }

        /// <summary>
        /// Return the SalesOne username when given the Ceylinco db username
        /// </summary>
        /// <param name="ceyUsername"></param>
        /// <returns></returns>
        public string GetUserMappingDetails(string ceyUsername)
        {
            try
            {
                using (SODataDataContext db = DataContextFactory.CreateContext())
                {
                    string soUsername = db.aspnet_Users.SingleOrDefault(p => p.IntranetUN.Equals(ceyUsername)).LoweredUserName;
                    return soUsername;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        
        public List<User> GetUsers(string sortExpression)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<UserEntity> query = db.UserEntities;

                if (sortExpression.Length > 0)
                {
                    string[] sort = sortExpression.Split(' ');
                    string sortColumn = sort[0];
                    string sortOrder = sort[1];

                    switch (sortColumn)
                    {
                        case "UserId":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.UserId);
                            else
                                query = query.OrderByDescending(c => c.UserId);
                            break;
                        case "Name":
                            if (sortOrder == "ASC")
                                query = query.OrderBy(c => c.Name);
                            else
                                query = query.OrderByDescending(c => c.Name);
                            break;
                    }
                }
                return query.Select(c => Mapper.ToUserObject(c)).ToList();
            }
        }

        public User GetUser(Guid userId)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                UserEntity user = db.UserEntities
                            .SingleOrDefault(p => p.UserId == userId);

                UsersInStructureEntity struc = db.UsersInStructureEntities.SingleOrDefault(p => p.UserId == userId);

                //return Mapper.ToUserObject(user, struc);
                return Mapper.ToUserObject(user);
            }
        }

        public User GetUser(string userName)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                
                UserEntity user = db.UserEntities
                            .SingleOrDefault(p => p.UserId == p.aspnet_User.UserId && p.aspnet_User.UserName == userName);

                IQueryable<UsersInStructureEntity> struc = from s in db.UsersInStructureEntities
                                               join u in db.aspnet_Users on s.UserId equals u.UserId
                                               where u.UserName == userName
                                               select s;                

                return Mapper.ToUserObject(user, struc.First());
                //return Mapper.ToUserObject(user);
            }
        }

        public UserInformation GetUserInformation(string userName)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                var info = from s in db.ufnGetUserInformation(userName)
                           select s;/* new
                            {
                                GroupId = s.GroupId,
                                GroupName = s.GroupName,
                                BranchId = s.BranchId,
                                BranchName = s.BranchName,
                                UnitId = s.UnitId,
                                UnitName = s.UnitName,
                                UserType = s.UserType,
                                NodeId = s.NodeId
                            };*/

              return  Mapper.ToUserInfoObject(info.First().GroupId,
                    info.First().GroupName,
                    info.First().BranchId,
                    info.First().BranchName,
                    info.First().UnitId,
                    info.First().UnitName,
                    info.First().UserType,
                    info.First().NodeId);
            }
        }

        public void InsertUser(User user)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    UserEntity entity = Mapper.ToUserEntity(user);
                    db.UserEntities.InsertOnSubmit(entity);
                    db.SubmitChanges();

                    user.UserId = entity.UserId;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to contact record was made before your changes.");
                }
                catch (Exception)
                {
                    throw new Exception("Unable to Insert contact " + user.Name);
                }
            }
        }

        public int UpdateUser(User user)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    UserEntity entity = Mapper.ToUserEntity(user);
                    UserEntity original = db.UserEntities.SingleOrDefault(p => p.UserId == user.UserId);

                    //db.UserEntities.Attach(entity,original);
                    original.UserId = user.UserId;
                    original.Name = user.Name;
                    original.Address1 = user.Address1;
                    original.Address2 = user.Address2;
                    original.IdType = Int32.Parse(user.IdType);
                    original.IdNo = user.IdNo;
                    original.City = user.City;
                    original.Country = Int32.Parse(user.Country);
                    original.ContactNo = user.Contact;
                    original.Gender = user.Gender;
                    original.DoneBy = user.DoneBy;
                    original.PostalCode = user.PostalCode;
                    

                    
                    db.SubmitChanges();
                    return 1;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to contact record was made before your changes.");
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }

        public int DeleteUser(User user)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    UserEntity entity = Mapper.ToUserEntity(user);
                    UsersInStructureEntity userSt = db.UsersInStructureEntities.SingleOrDefault(p => p.UserId == user.UserId);

                    if (userSt != null)
                    {
                        db.UsersInStructureEntities.DeleteOnSubmit(userSt);
                        db.SubmitChanges();
                    }
                    
                    db.UserEntities.Attach(entity, false);
                    db.UserEntities.DeleteOnSubmit(entity);
                    db.SubmitChanges();

                    return 1;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to contact record was made before your changes.");
                }
                catch (Exception)
                {
                    return 0;
                }
            }
        }

        public List<string> GetUsersInUnits(int unitID)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<string> query = from user in db.UserEntities
                          join pos in db.UsersInStructureEntities
                          on user.UserId
                          equals pos.UserId
                          where pos.UserTypeId == 4 && pos.NodeId == unitID && user.SOCode != null
                          select user.SOCode;

                return query.Distinct().ToList();                
            }
        }

        public List<string> GetUsersInUnits(string sortExpression, string userName)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<string> query = from user in db.UserEntities
                                           join usersInStructure in db.UsersInStructureEntities on user.UserId equals usersInStructure.UserId
                                           join  unit in db.UnitEntities on usersInStructure.NodeId equals unit.UnitId where usersInStructure.UserTypeId==4
                                           join usersInInfrastructure in db.UsersInStructureEntities on unit.UnitId equals usersInInfrastructure.NodeId
                                           where usersInInfrastructure.UserTypeId == 4
                                           join users in db.aspnet_Users on usersInInfrastructure.UserId equals users.UserId
                                           where users.UserName == userName
                                           select user.SOCode;

                return query.ToList();
            }
        }

        public List<User> GetUsersInStructure(int userTypeId,int nodeId,int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                var query = from user in db.UserEntities
                            join pos in db.UsersInStructureEntities
                            on user.UserId equals pos.UserId
                            join a in db.aspnet_Memberships on user.UserId equals a.UserId
                            where pos.UserTypeId == userTypeId && pos.NodeId == nodeId && a.IsApproved == true && a.IsLockedOut == false
                            select user;

                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToUserObject(c)).ToList();
            }
        }

        public List<User> GetUsersInHQ(int userTypeId,int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                var query = from user in db.UserEntities
                            join pos in db.UsersInStructureEntities
                            on user.UserId equals pos.UserId
                            join a in db.aspnet_Memberships on user.UserId equals a.UserId
                            where pos.UserTypeId == userTypeId && a.IsApproved == true && a.IsLockedOut == false
                            select user;

                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToUserObject(c)).ToList();
            }
        }


        public List<User> GetSearchUsers(string name, string userId, int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {

                var query = from c in db.UserEntities
                            join u in db.aspnet_Memberships
                            on c.UserId equals u.UserId
                            join au in db.aspnet_Users on u.UserId equals au.UserId
                            where SqlMethods.Like(c.Name, name) && SqlMethods.Like(au.UserName, userId) && u.IsApproved != false && u.IsLockedOut != true && c.IsDeleted != true
                            select c;

                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToUserObject(c)).ToList();
            }
        }


        public List<User> GetBlockedUsers(string name, int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {

                var query = from c in db.UserEntities
                            join u in db.aspnet_Memberships
                            on c.UserId equals u.UserId
                            where SqlMethods.Like(c.Name, name) && ((u.IsApproved == false) || (u.IsLockedOut == true)) && c.IsDeleted != true
                            select c;

                var pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToUserObject(c)).ToList();
            }
        }



        public int[] GetStructureForUser(string userName)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                int[] structure = new int[2];
                structure[0] = db.UsersInStructureEntities.SingleOrDefault(p => p.UserEntity.aspnet_User.UserName == userName).UserTypeId;
                structure[1] = db.UsersInStructureEntities.SingleOrDefault(p => p.UserEntity.aspnet_User.UserName == userName).NodeId;

                return structure;
            }
        }


        public void InsertToUserInStructure(Guid userId, short userType, int nodeId)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {

                UsersInStructureEntity usrSt = new UsersInStructureEntity();
                usrSt.UserId = userId;
                usrSt.UserTypeId = userType;
                usrSt.NodeId = nodeId;

                db.UsersInStructureEntities.InsertOnSubmit(usrSt);
                db.SubmitChanges();

            }
        }


        public int UpdateUserInStructure(Guid userId, short userType, int nodeId)
        {

            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {
                    UsersInStructureEntity usrSt = new UsersInStructureEntity();
                    usrSt.UserId = userId;
                    usrSt.UserTypeId = userType;
                    usrSt.NodeId = nodeId;

                    db.UsersInStructureEntities.Attach(usrSt,true);
                    db.SubmitChanges();
                    return 1;
                }
                catch (ChangeConflictException)
                {
                    throw new Exception("A change to contact record was made before your changes.");
                }
                catch (Exception)
                {
                    return 0;
                }
            }

        }


        public List<User> GetUsersForSOcode(int unitID, int month, int year, int pageNo)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {

                #region commented

                //IQueryable<UserEntity> query = from user in db.UserEntities
                //                               join uis in db.UsersInStructureEntities
                //                               on user.UserId equals uis.UserId
                //                               where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)

                //                               join sa in db.SalesActivityPolicyEntities
                //                               on user.SOCode equals sa.SOCode
                //                               where sa.ApptDate.Month != month || sa.ApptDate.Year != year 

                //                               select user;


                //                              where (from sa1 in db.SalesActivityPolicyEntities
                //                                       where sa1.ApptDate.Month == month && sa1.ApptDate.Year == year && sa1.SOCode == user.SOCode
                //                                       select sa1).Count() == 0                                               
                //                               select user).Distinct();


                //var query = (from p in dc.GetTable<Person>()
                //             join pa in dc.GetTable<PersonAddress>() on p.Id equals pa.PersonId into tempAddresses
                //             from addresses in tempAddresses.DefaultIfEmpty()
                //             select new { p.FirstName, p.LastName, addresses.State });
                #endregion 


                IQueryable<UserEntity> query = (from user in db.UserEntities
                                                join uis in db.UsersInStructureEntities
                                                 on user.UserId equals uis.UserId
                                                where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)

                                                join sa in db.SalesActivityPolicyEntities
                                                on user.SOCode equals sa.SOCode into tempPol

                                                join sa in db.SalesActivityProspectEntities
                                                on user.SOCode equals sa.SOCode into tempPro

                                                where ((from tp in tempPol.DefaultIfEmpty()
                                                        where tp.ApptDate.Month == month && tp.ApptDate.Year == year && tp.SOCode == user.SOCode
                                                        select tp).Count() == 0) && ((from tp1 in tempPro.DefaultIfEmpty()
                                                                                      where tp1.ApptDate.Month == month && tp1.ApptDate.Year == year && tp1.SOCode == user.SOCode
                                                                                      select tp1).Count() == 0)
                                                select user); 





                IQueryable<UserEntity> pageData = query.Skip((pageNo - 1) * pageSize).Take(pageSize);

                return pageData.Select(c => Mapper.ToUserObject(c)).ToList();


            }
        }


        public List<User> GetUsersForSOcode(int unitID, int month, int year)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {

                #region commented

                //IQueryable<UserEntity> query = from user in db.UserEntities
                //                               join uis in db.UsersInStructureEntities
                //                               on user.UserId equals uis.UserId
                //                               where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)

                //                               join sa in db.SalesActivityPolicyEntities
                //                               on user.SOCode equals sa.SOCode
                //                               where sa.ApptDate.Month != month || sa.ApptDate.Year != year 

                //                               select user;


                //IQueryable<UserEntity> query = from user in db.UserEntities
                //                               join uis in db.UsersInStructureEntities
                //                               on user.UserId equals uis.UserId
                //                               //where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)


                //                               join sa in db.SalesActivityPolicyEntities
                //                               on user.SOCode equals sa.SOCode
                //                               where ((from sa1 in db.SalesActivityPolicyEntities
                //                                       where sa1.ApptDate.Month == month && sa1.ApptDate.Year == year && sa1.SOCode == user.SOCode
                //                                       select sa1).Count() == 0)
                //                               select user;

                //return query.Select(c => Mapper.ToUserObject(c)).ToList();
                #endregion 


                IQueryable<UserEntity> query = (from user in db.UserEntities
                                               join uis in db.UsersInStructureEntities
                                                on user.UserId equals uis.UserId
                                               where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)

                                               join sa in db.SalesActivityPolicyEntities
                                               on user.SOCode equals sa.SOCode into tempPol

                                               join sa in db.SalesActivityProspectEntities
                                               on user.SOCode equals sa.SOCode into tempPro

                                                where ((from tp in tempPol.DefaultIfEmpty()
                                                      where tp.ApptDate.Month == month && tp.ApptDate.Year == year && tp.SOCode == user.SOCode
                                                        select tp).Count() == 0) && ((from tp1 in tempPro.DefaultIfEmpty()
                                                                                      where tp1.ApptDate.Month == month && tp1.ApptDate.Year == year && tp1.SOCode == user.SOCode
                                                                                      select tp1).Count() == 0) 
                                               select user); 

                #region commented
                //where sa1.ApptDate.Month == month && sa1.ApptDate.Year == year && sa1.SOCode == user.SOCode
                 //                              //        select sa1).Count() == 0)

                //((from sa1 in db.SalesActivityPolicyEntities
                ////                                       where sa1.ApptDate.Month == month && sa1.ApptDate.Year == year && sa1.SOCode == user.SOCode && uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null 
                ////                                       select sa1).Count() == 0)

                //IQueryable<UserEntity> query = from user in db.UserEntities
                //                               join uis in db.UsersInStructureEntities
                //                               on user.UserId equals uis.UserId
                //                               join sa in db.SalesActivityPolicyEntities
                //                               on user.SOCode equals sa.SOCode
                //                               //where (uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null)


                                               
                //                               where ((from sa1 in db.SalesActivityPolicyEntities
                //                                       where sa1.ApptDate.Month == month && sa1.ApptDate.Year == year && sa1.SOCode == user.SOCode && uis.UserTypeId == 4 && uis.NodeId == unitID && user.SOCode != null 
                //                                       select sa1).Count() == 0)
                //                               select user;

                #endregion 

                return query.Select(c => Mapper.ToUserObject(c)).ToList();





            }
        }  
             
        
        public bool IsPermitted(string userName, string URL)
        {
            List<TaskCredentials> tasks = GetUserCredentials(userName, URL);            
            return tasks.Count > 0 ? true : false;
        }

        public List<TaskCredentials> GetUserCredentials(string userName, string URL)
        {
            using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                IQueryable<TaskPermissionEntity> query = (from cred in db.TaskPermissionEntities
                                                          where cred.TaskId == (
                                                                from url in db.PagesInTaskEntities
                                                                where url.PageURL == URL
                                                                select url.TaskId).SingleOrDefault()
                                                          select cred)
                                                       .Intersect(
                                                           from role in db.aspnet_RoleEntities
                                                           join rolein in db.aspnet_UsersInRoles on role.RoleId equals rolein.RoleId
                                                           join user in db.aspnet_Users on rolein.UserId equals user.UserId
                                                           where user.UserName == userName
                                                           join cred in db.TaskPermissionEntities on role.RoleId equals cred.RoleId
                                                           select cred);

                
                return query.Select(c => Mapper.ToTaskPermissionObject(c)).ToList();
            }
        }

       public void AddUser(string[] user, User userObj, string[] roles,int userType,int node)
        {
           using (SODataDataContext db = DataContextFactory.CreateContext())
            {
                try
                {

                    System.Guid? gg = Guid.NewGuid();

                    string[] usrProps = user;
                    

                    MyMembershipProvider mm = new MyMembershipProvider();
                    System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
                    byte[] bArr = mm.EncryptPassword(encoding.GetBytes(usrProps[11]));

                   

                    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                    string pw = enc.GetString(bArr);


                    //db.aspnet_Membership_CreateUser(Membership.ApplicationName, usrProps[10], pw, string.Empty, usrProps[12], usrProps[13], usrProps[14], true, DateTime.Today.ToUniversalTime(), DateTime.Now.Date, 0, 2, ref gg);
                    MembershipCreateStatus status;
                    MembershipUser newUs = Membership.CreateUser(usrProps[10], usrProps[11], usrProps[12],null,null, true, out status);


                    if (newUs == null)
                    {
                        switch (status)
                        {
                            case MembershipCreateStatus.DuplicateUserName:
                                throw new Exception("23");
                                break;
                            case MembershipCreateStatus.DuplicateEmail:
                                throw new Exception("24");
                                break;
                            case MembershipCreateStatus.InvalidPassword:
                                throw new Exception("25");
                                break;
                            case MembershipCreateStatus.InvalidEmail:
                                throw new Exception("26");
                                break;
                            case MembershipCreateStatus.InvalidAnswer:
                                throw new Exception("27");
                                break;
                            case MembershipCreateStatus.InvalidQuestion:
                                throw new Exception("28");
                                break;
                            case MembershipCreateStatus.InvalidUserName:
                                throw new Exception("29");
                                break;
                            case MembershipCreateStatus.ProviderError:
                                throw new Exception("30");
                                break;
                            case MembershipCreateStatus.UserRejected:
                                throw new Exception("31");
                                break;
                            default:
                                throw new Exception("32");

                        }
                    }



                    //userObj.UserId = (Guid)gg;
                    MembershipUser usr = Membership.GetUser(usrProps[10]);
                    Guid userGuuid = (Guid)usr.ProviderUserKey;
                    userObj.UserId = userGuuid;
                    userObj.DoneBy = System.Web.HttpContext.Current.User.Identity.Name;

                    UserEntity entity = Mapper.ToUserEntity(userObj);
                    db.UserEntities.InsertOnSubmit(entity);

                    for (int i = 0; i < roles.Length; i++)
                    {
                        db.aspnet_UsersInRoles_AddUsersToRoles(Membership.ApplicationName, usrProps[10], roles[i], DateTime.Today.ToUniversalTime());
                    }

                    // Suren Manawatta
                    // 2012-10-31
                    // Add user's intranet username to aspnetUsers table
                    aspnet_User aspUsr = db.aspnet_Users
                               .SingleOrDefault(p => p.LoweredUserName == usrProps[10].ToLower());
                    aspUsr.IntranetUN = usrProps[13];
                    db.SubmitChanges();


                    UsersInStructureEntity usrSt = new UsersInStructureEntity();
                    //usrSt.UserId = (Guid)gg;
                    usrSt.UserId = userGuuid;
                    usrSt.UserTypeId = (short)userType;
                    usrSt.NodeId = node;

                    db.UsersInStructureEntities.InsertOnSubmit(usrSt);

                    //MembershipUser mu = Membership.GetUser(usrProps[10]);
                    //mu.ChangePassword(usrProps[11],mu.ResetPassword(usrProps[14]));

                    db.SubmitChanges();
                    userObj.UserId = entity.UserId; 
                }
                catch (Exception ex)
                {

                    MembershipUser usr = Membership.GetUser(user[10]);
                    if (usr != null)
                    {
                        Membership.DeleteUser(user[10]);
                    }

                    throw new Exception(ex.Message);
                }
            }
        }





       
       public class MyMembershipProvider : System.Web.Security.MembershipProvider
        {
        /// <summary>
        /// Allows public access to protected member
        /// </summary>
        /// <param name="encodedPassword"></param>
        /// <returns></returns>
        public new byte[] DecryptPassword(byte[] encodedPassword)
        {
        return base.DecryptPassword(encodedPassword);
        }

        /// <summary>
        /// Allows public access to protected member
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public new byte[] EncryptPassword(byte[] password)
        {
        return base.EncryptPassword(password);
        }




        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            throw new NotImplementedException();
        }
        }












     public static string HashCode(string str)  
    {


        string rethash = "";
        try
        {

            System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
            System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
            byte[] combined = encoder.GetBytes(str);
            hash.ComputeHash(combined);
            rethash = Convert.ToBase64String(hash.Hash);
        }
        catch (Exception ex)
        {
            string strerr = "Error in HashCode : " + ex.Message;
        }
        return rethash;  
   }



     public class RijndaelSimple
     {
        
         public static string Encrypt(string plainText,
                                      string passPhrase,
                                      string saltValue,
                                      string hashAlgorithm,
                                      int passwordIterations,
                                      string initVector,
                                      int keySize)
         {
          
             byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
             byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

             byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

             
             PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                             passPhrase,
                                                             saltValueBytes,
                                                             hashAlgorithm,
                                                             passwordIterations);

             
             byte[] keyBytes = password.GetBytes(keySize / 8);

             
             RijndaelManaged symmetricKey = new RijndaelManaged();

             
             symmetricKey.Mode = CipherMode.CBC;

            
             ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                              keyBytes,
                                                              initVectorBytes);

             // Define memory stream which will be used to hold encrypted data.
             MemoryStream memoryStream = new MemoryStream();

             // Define cryptographic stream (always use Write mode for encryption).
             CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                          encryptor,
                                                          CryptoStreamMode.Write);
             // Start encrypting.
             cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);

             // Finish encrypting.
             cryptoStream.FlushFinalBlock();

             // Convert our encrypted data from a memory stream into a byte array.
             byte[] cipherTextBytes = memoryStream.ToArray();

             // Close both streams.
             memoryStream.Close();
             cryptoStream.Close();

             // Convert encrypted data into a base64-encoded string.
             string cipherText = Convert.ToBase64String(cipherTextBytes);

             // Return encrypted string.
             return cipherText;
         }

         
         public static string Decrypt(string cipherText,
                                      string passPhrase,
                                      string saltValue,
                                      string hashAlgorithm,
                                      int passwordIterations,
                                      string initVector,
                                      int keySize)
         {
            
             byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
             byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

             
             byte[] cipherTextBytes = Convert.FromBase64String(cipherText);

            
             PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                             passPhrase,
                                                             saltValueBytes,
                                                             hashAlgorithm,
                                                             passwordIterations);

             // Use the password to generate pseudo-random bytes for the encryption
             // key. Specify the size of the key in bytes (instead of bits).
             byte[] keyBytes = password.GetBytes(keySize / 8);

             // Create uninitialized Rijndael encryption object.
             RijndaelManaged symmetricKey = new RijndaelManaged();

             // It is reasonable to set encryption mode to Cipher Block Chaining
             // (CBC). Use default options for other symmetric key parameters.
             symmetricKey.Mode = CipherMode.CBC;

             // Generate decryptor from the existing key bytes and initialization 
             // vector. Key size will be defined based on the number of the key 
             // bytes.
             ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
                                                              keyBytes,
                                                              initVectorBytes);

             // Define memory stream which will be used to hold encrypted data.
             MemoryStream memoryStream = new MemoryStream(cipherTextBytes);

             // Define cryptographic stream (always use Read mode for encryption).
             CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                           decryptor,
                                                           CryptoStreamMode.Read);

             // Since at this point we don't know what the size of decrypted data
             // will be, allocate the buffer long enough to hold ciphertext;
             // plaintext is never longer than ciphertext.
             byte[] plainTextBytes = new byte[cipherTextBytes.Length];

             // Start decrypting.
             int decryptedByteCount = cryptoStream.Read(plainTextBytes,
                                                        0,
                                                        plainTextBytes.Length);

             // Close both streams.
             memoryStream.Close();
             cryptoStream.Close();

             // Convert decrypted data into a string. 
             // Let us assume that the original plaintext string was UTF8-encoded.
             string plainText = Encoding.UTF8.GetString(plainTextBytes,
                                                        0,
                                                        decryptedByteCount);

             // Return decrypted string.   
             return plainText;
         }
     }



    }
}
